import asyncio
from bleak import BleakScanner, BleakClient

SERVICE_UUID = '0000ffff-0000-1000-8000-00805f9b34fb'
WRITE_CHAR_UUID = '0000ff01-0000-1000-8000-00805f9b34fb'
NOTIFY_CHAR_UUID = '0000ff02-0000-1000-8000-00805f9b34fb'

async def main():
    print('扫描包含服务的设备…')

    def filter_fn(d, ad):
        uuids = (ad.service_uuids or [])
        return any((u or '').lower() == SERVICE_UUID for u in uuids)

    device = await BleakScanner.find_device_by_filter(filter_fn, timeout=10.0)
    if not device:
        print('未找到设备，请确认手机端在广播且UUID一致。')
        return

    async with BleakClient(device) as client:
        print('已连接到:', device.name or device.address)

        def on_notify(_, data: bytearray):
            try:
                text = data.decode('utf-8')
            except Exception:
                text = str(list(data))
            print('收到通知:', text)

        await client.start_notify(NOTIFY_CHAR_UUID, on_notify)
        print('已订阅 FF02 通知。')

        while True:
            s = input('输入要发送到 FF01 的文本（回车发送，空行退出）：').strip()
            if not s:
                break
            await client.write_gatt_char(WRITE_CHAR_UUID, s.encode('utf-8'))
            print('已写入 FF01:', s)

        await client.stop_notify(NOTIFY_CHAR_UUID)
        print('已停止订阅，准备断开。')

if __name__ == '__main__':
    asyncio.run(main())